package cn.com.sinosoft.ares.common.util;

/*
Copyright (c) 2008 JSON.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

The Software shall be used for Good, not Evil.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/**
 * This provides static methods to tools an XMLTools text into a JSONArrayTools or
 * JSONObjectTools, and to covert a JSONArrayTools or JSONObjectTools into an XMLTools text using
 * the JsonML transform.
 *
 * @author JSON.org
 * @version 2016-01-30
 */
public class JSONMLTools {
    /**
     * Parse XMLTools values and store them in a JSONArrayTools.
     * @param x       The XMLTokenerTools containing the source string.
     * @param arrayForm true if array form, false if object form.
     * @param ja      The JSONArrayTools that is containing the current tag or null
     *     if we are at the outermost level.
     * @param keepStrings	Don't type-tools text nodes and attribute values
     * @return A JSONArrayTools if the value is the outermost tag, otherwise null.
     * @throws JSONExceptionTools
     */
    private static Object parse(
        XMLTokenerTools x,
        boolean    arrayForm,
        JSONArrayTools ja,
        boolean keepStrings
    ) throws JSONExceptionTools {
        String attribute;
        char       c;
        String closeTag = null;
        int        i;
        JSONArrayTools newja = null;
        JSONObjectTools newjo = null;
        Object token;
        String tagName = null;

// Test for and skip past these forms:
//      <!-- ... -->
//      <![  ... ]]>
//      <!   ...   >
//      <?   ...  ?>

        while (true) {
            if (!x.more()) {
                throw x.syntaxError("Bad XMLTools");
            }
            token = x.nextContent();
            if (token == XMLTools.LT) {
                token = x.nextToken();
                if (token instanceof Character) {
                    if (token == XMLTools.SLASH) {

// Close tag </

                        token = x.nextToken();
                        if (!(token instanceof String)) {
                            throw new JSONExceptionTools(
                                    "Expected a closing name instead of '" +
                                    token + "'.");
                        }
                        if (x.nextToken() != XMLTools.GT) {
                            throw x.syntaxError("Misshaped close tag");
                        }
                        return token;
                    } else if (token == XMLTools.BANG) {

// <!

                        c = x.next();
                        if (c == '-') {
                            if (x.next() == '-') {
                                x.skipPast("-->");
                            } else {
                                x.back();
                            }
                        } else if (c == '[') {
                            token = x.nextToken();
                            if (token.equals("CDATA") && x.next() == '[') {
                                if (ja != null) {
                                    ja.put(x.nextCDATA());
                                }
                            } else {
                                throw x.syntaxError("Expected 'CDATA['");
                            }
                        } else {
                            i = 1;
                            do {
                                token = x.nextMeta();
                                if (token == null) {
                                    throw x.syntaxError("Missing '>' after '<!'.");
                                } else if (token == XMLTools.LT) {
                                    i += 1;
                                } else if (token == XMLTools.GT) {
                                    i -= 1;
                                }
                            } while (i > 0);
                        }
                    } else if (token == XMLTools.QUEST) {

// <?

                        x.skipPast("?>");
                    } else {
                        throw x.syntaxError("Misshaped tag");
                    }

// Open tag <

                } else {
                    if (!(token instanceof String)) {
                        throw x.syntaxError("Bad tagName '" + token + "'.");
                    }
                    tagName = (String)token;
                    newja = new JSONArrayTools();
                    newjo = new JSONObjectTools();
                    if (arrayForm) {
                        newja.put(tagName);
                        if (ja != null) {
                            ja.put(newja);
                        }
                    } else {
                        newjo.put("tagName", tagName);
                        if (ja != null) {
                            ja.put(newjo);
                        }
                    }
                    token = null;
                    for (;;) {
                        if (token == null) {
                            token = x.nextToken();
                        }
                        if (token == null) {
                            throw x.syntaxError("Misshaped tag");
                        }
                        if (!(token instanceof String)) {
                            break;
                        }

// attribute = value

                        attribute = (String)token;
                        if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) {
                            throw x.syntaxError("Reserved attribute.");
                        }
                        token = x.nextToken();
                        if (token == XMLTools.EQ) {
                            token = x.nextToken();
                            if (!(token instanceof String)) {
                                throw x.syntaxError("Missing value");
                            }
                            newjo.accumulate(attribute, keepStrings ? ((String)token) : XMLTools.stringToValue((String)token));
                            token = null;
                        } else {
                            newjo.accumulate(attribute, "");
                        }
                    }
                    if (arrayForm && newjo.length() > 0) {
                        newja.put(newjo);
                    }

// Empty tag <.../>

                    if (token == XMLTools.SLASH) {
                        if (x.nextToken() != XMLTools.GT) {
                            throw x.syntaxError("Misshaped tag");
                        }
                        if (ja == null) {
                            if (arrayForm) {
                                return newja;
                            }
                            return newjo;
                        }

// Content, between <...> and </...>

                    } else {
                        if (token != XMLTools.GT) {
                            throw x.syntaxError("Misshaped tag");
                        }
                        closeTag = (String)parse(x, arrayForm, newja, keepStrings);
                        if (closeTag != null) {
                            if (!closeTag.equals(tagName)) {
                                throw x.syntaxError("Mismatched '" + tagName +
                                        "' and '" + closeTag + "'");
                            }
                            tagName = null;
                            if (!arrayForm && newja.length() > 0) {
                                newjo.put("childNodes", newja);
                            }
                            if (ja == null) {
                                if (arrayForm) {
                                    return newja;
                                }
                                return newjo;
                            }
                        }
                    }
                }
            } else {
                if (ja != null) {
                    ja.put(token instanceof String
                        ? keepStrings ? XMLTools.unescape((String)token) : XMLTools.stringToValue((String)token)
                        : token);
                }
            }
        }
    }


    /**
     * Convert a well-formed (but not necessarily valid) XMLTools string into a
     * JSONArrayTools using the JsonML transform. Each XMLTools tag is represented as
     * a JSONArrayTools in which the first element is the tag name. If the tag has
     * attributes, then the second element will be JSONObjectTools containing the
     * name/value pairs. If the tag contains children, then strings and
     * JSONArrays will represent the child tags.
     * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
     * @param string The source string.
     * @return A JSONArrayTools containing the structured data from the XMLTools string.
     * @throws JSONExceptionTools Thrown on error converting to a JSONArrayTools
     */
    public static JSONArrayTools toJSONArray(String string) throws JSONExceptionTools {
        return (JSONArrayTools)parse(new XMLTokenerTools(string), true, null, false);
    }


    /**
     * Convert a well-formed (but not necessarily valid) XMLTools string into a
     * JSONArrayTools using the JsonML transform. Each XMLTools tag is represented as
     * a JSONArrayTools in which the first element is the tag name. If the tag has
     * attributes, then the second element will be JSONObjectTools containing the
     * name/value pairs. If the tag contains children, then strings and
     * JSONArrays will represent the child tags.
     * As opposed to toJSONArray this method does not attempt to tools
     * any text node or attribute value to any type 
     * but just leaves it as a string.
     * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
     * @param string The source string.
     * @param keepStrings If true, then values will not be coerced into boolean
     *  or numeric values and will instead be left as strings
     * @return A JSONArrayTools containing the structured data from the XMLTools string.
     * @throws JSONExceptionTools Thrown on error converting to a JSONArrayTools
     */
    public static JSONArrayTools toJSONArray(String string, boolean keepStrings) throws JSONExceptionTools {
        return (JSONArrayTools)parse(new XMLTokenerTools(string), true, null, keepStrings);
    }


    /**
     * Convert a well-formed (but not necessarily valid) XMLTools string into a
     * JSONArrayTools using the JsonML transform. Each XMLTools tag is represented as
     * a JSONArrayTools in which the first element is the tag name. If the tag has
     * attributes, then the second element will be JSONObjectTools containing the
     * name/value pairs. If the tag contains children, then strings and
     * JSONArrays will represent the child content and tags.
     * As opposed to toJSONArray this method does not attempt to tools
     * any text node or attribute value to any type 
     * but just leaves it as a string.
     * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
     * @param x An XMLTokenerTools.
     * @param keepStrings If true, then values will not be coerced into boolean
     *  or numeric values and will instead be left as strings
     * @return A JSONArrayTools containing the structured data from the XMLTools string.
     * @throws JSONExceptionTools Thrown on error converting to a JSONArrayTools
     */
    public static JSONArrayTools toJSONArray(XMLTokenerTools x, boolean keepStrings) throws JSONExceptionTools {
        return (JSONArrayTools)parse(x, true, null, keepStrings);
    }


    /**
     * Convert a well-formed (but not necessarily valid) XMLTools string into a
     * JSONArrayTools using the JsonML transform. Each XMLTools tag is represented as
     * a JSONArrayTools in which the first element is the tag name. If the tag has
     * attributes, then the second element will be JSONObjectTools containing the
     * name/value pairs. If the tag contains children, then strings and
     * JSONArrays will represent the child content and tags.
     * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
     * @param x An XMLTokenerTools.
     * @return A JSONArrayTools containing the structured data from the XMLTools string.
     * @throws JSONExceptionTools Thrown on error converting to a JSONArrayTools
     */
    public static JSONArrayTools toJSONArray(XMLTokenerTools x) throws JSONExceptionTools {
        return (JSONArrayTools)parse(x, true, null, false);
    }


    /**
     * Convert a well-formed (but not necessarily valid) XMLTools string into a
     * JSONObjectTools using the JsonML transform. Each XMLTools tag is represented as
     * a JSONObjectTools with a "tagName" property. If the tag has attributes, then
     * the attributes will be in the JSONObjectTools as properties. If the tag
     * contains children, the object will have a "childNodes" property which
     * will be an array of strings and JsonML JSONObjects.

     * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
     * @param string The XMLTools source text.
     * @return A JSONObjectTools containing the structured data from the XMLTools string.
     * @throws JSONExceptionTools Thrown on error converting to a JSONObjectTools
     */
    public static JSONObjectTools toJSONObject(String string) throws JSONExceptionTools {
        return (JSONObjectTools)parse(new XMLTokenerTools(string), false, null, false);
    }
    
    
    /**
     * Convert a well-formed (but not necessarily valid) XMLTools string into a
     * JSONObjectTools using the JsonML transform. Each XMLTools tag is represented as
     * a JSONObjectTools with a "tagName" property. If the tag has attributes, then
     * the attributes will be in the JSONObjectTools as properties. If the tag
     * contains children, the object will have a "childNodes" property which
     * will be an array of strings and JsonML JSONObjects.

     * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
     * @param string The XMLTools source text.
     * @param keepStrings If true, then values will not be coerced into boolean
     *  or numeric values and will instead be left as strings
     * @return A JSONObjectTools containing the structured data from the XMLTools string.
     * @throws JSONExceptionTools Thrown on error converting to a JSONObjectTools
     */
    public static JSONObjectTools toJSONObject(String string, boolean keepStrings) throws JSONExceptionTools {
        return (JSONObjectTools)parse(new XMLTokenerTools(string), false, null, keepStrings);
    }

    
    /**
     * Convert a well-formed (but not necessarily valid) XMLTools string into a
     * JSONObjectTools using the JsonML transform. Each XMLTools tag is represented as
     * a JSONObjectTools with a "tagName" property. If the tag has attributes, then
     * the attributes will be in the JSONObjectTools as properties. If the tag
     * contains children, the object will have a "childNodes" property which
     * will be an array of strings and JsonML JSONObjects.

     * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
     * @param x An XMLTokenerTools of the XMLTools source text.
     * @return A JSONObjectTools containing the structured data from the XMLTools string.
     * @throws JSONExceptionTools Thrown on error converting to a JSONObjectTools
     */
    public static JSONObjectTools toJSONObject(XMLTokenerTools x) throws JSONExceptionTools {
           return (JSONObjectTools)parse(x, false, null, false);
    }


    /**
     * Convert a well-formed (but not necessarily valid) XMLTools string into a
     * JSONObjectTools using the JsonML transform. Each XMLTools tag is represented as
     * a JSONObjectTools with a "tagName" property. If the tag has attributes, then
     * the attributes will be in the JSONObjectTools as properties. If the tag
     * contains children, the object will have a "childNodes" property which
     * will be an array of strings and JsonML JSONObjects.

     * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
     * @param x An XMLTokenerTools of the XMLTools source text.
     * @param keepStrings If true, then values will not be coerced into boolean
     *  or numeric values and will instead be left as strings
     * @return A JSONObjectTools containing the structured data from the XMLTools string.
     * @throws JSONExceptionTools Thrown on error converting to a JSONObjectTools
     */
    public static JSONObjectTools toJSONObject(XMLTokenerTools x, boolean keepStrings) throws JSONExceptionTools {
           return (JSONObjectTools)parse(x, false, null, keepStrings);
    }


    /**
     * Reverse the JSONMLTools transformation, making an XMLTools text from a JSONArrayTools.
     * @param ja A JSONArrayTools.
     * @return An XMLTools string.
     * @throws JSONExceptionTools Thrown on error converting to a string
     */
    public static String toString(JSONArrayTools ja) throws JSONExceptionTools {
        int                 i;
        JSONObjectTools jo;
        int                 length;
        Object object;
        StringBuilder sb = new StringBuilder();
        String tagName;

// Emit <tagName

        tagName = ja.getString(0);
        XMLTools.noSpace(tagName);
        tagName = XMLTools.escape(tagName);
        sb.append('<');
        sb.append(tagName);

        object = ja.opt(1);
        if (object instanceof JSONObjectTools) {
            i = 2;
            jo = (JSONObjectTools)object;

// Emit the attributes

            // Don't use the new entrySet API to maintain Android support
            for (final String key : jo.keySet()) {
                final Object value = jo.opt(key);
                XMLTools.noSpace(key);
                if (value != null) {
                    sb.append(' ');
                    sb.append(XMLTools.escape(key));
                    sb.append('=');
                    sb.append('"');
                    sb.append(XMLTools.escape(value.toString()));
                    sb.append('"');
                }
            }
        } else {
            i = 1;
        }

// Emit content in body

        length = ja.length();
        if (i >= length) {
            sb.append('/');
            sb.append('>');
        } else {
            sb.append('>');
            do {
                object = ja.get(i);
                i += 1;
                if (object != null) {
                    if (object instanceof String) {
                        sb.append(XMLTools.escape(object.toString()));
                    } else if (object instanceof JSONObjectTools) {
                        sb.append(toString((JSONObjectTools)object));
                    } else if (object instanceof JSONArrayTools) {
                        sb.append(toString((JSONArrayTools)object));
                    } else {
                        sb.append(object.toString());
                    }
                }
            } while (i < length);
            sb.append('<');
            sb.append('/');
            sb.append(tagName);
            sb.append('>');
        }
        return sb.toString();
    }

    /**
     * Reverse the JSONMLTools transformation, making an XMLTools text from a JSONObjectTools.
     * The JSONObjectTools must contain a "tagName" property. If it has children,
     * then it must have a "childNodes" property containing an array of objects.
     * The other properties are attributes with string values.
     * @param jo A JSONObjectTools.
     * @return An XMLTools string.
     * @throws JSONExceptionTools Thrown on error converting to a string
     */
    public static String toString(JSONObjectTools jo) throws JSONExceptionTools {
        StringBuilder sb = new StringBuilder();
        int                 i;
        JSONArrayTools ja;
        int                 length;
        Object object;
        String tagName;
        Object value;

//Emit <tagName

        tagName = jo.optString("tagName");
        if (tagName == null) {
            return XMLTools.escape(jo.toString());
        }
        XMLTools.noSpace(tagName);
        tagName = XMLTools.escape(tagName);
        sb.append('<');
        sb.append(tagName);

//Emit the attributes

        // Don't use the new entrySet API to maintain Android support
        for (final String key : jo.keySet()) {
            if (!"tagName".equals(key) && !"childNodes".equals(key)) {
                XMLTools.noSpace(key);
                value = jo.opt(key);
                if (value != null) {
                    sb.append(' ');
                    sb.append(XMLTools.escape(key));
                    sb.append('=');
                    sb.append('"');
                    sb.append(XMLTools.escape(value.toString()));
                    sb.append('"');
                }
            }
        }

//Emit content in body

        ja = jo.optJSONArray("childNodes");
        if (ja == null) {
            sb.append('/');
            sb.append('>');
        } else {
            sb.append('>');
            length = ja.length();
            for (i = 0; i < length; i += 1) {
                object = ja.get(i);
                if (object != null) {
                    if (object instanceof String) {
                        sb.append(XMLTools.escape(object.toString()));
                    } else if (object instanceof JSONObjectTools) {
                        sb.append(toString((JSONObjectTools)object));
                    } else if (object instanceof JSONArrayTools) {
                        sb.append(toString((JSONArrayTools)object));
                    } else {
                        sb.append(object.toString());
                    }
                }
            }
            sb.append('<');
            sb.append('/');
            sb.append(tagName);
            sb.append('>');
        }
        return sb.toString();
    }
}
